package com.travelsky.login.resource.exception;

import com.google.common.base.Strings;
import com.travelsky.login.api.BaseResponse;
import com.travelsky.login.domain.BusinessException;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
@Order(1)
public class BusinessExceptionHandler {

  @ResponseBody
  @ExceptionHandler(value = BusinessException.class)
  @ResponseStatus(HttpStatus.OK)
  public BaseResponse handler(BusinessException ex) {
    return parsePreconditionsException(ex);
  }

  private BaseResponse parsePreconditionsException(BusinessException ex) {
    String message = ex.getMessage();
    BaseResponse.Error error = new BaseResponse.Error();
    if (!Strings.isNullOrEmpty(message)) {
      error.setCode(ex.getCode());
      error.setMsg(ex.getMsg());
    }
    return new BaseResponse(error);
  }

}
